#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
PSQI文件对比脚本
对比修复前后的PSQI数据文件，验证修复效果
"""

import json
import os

def load_json_file(file_path):
    """加载JSON文件"""
    try:
        with open(file_path, 'r', encoding='utf-8') as f:
            return json.load(f)
    except Exception as e:
        print(f"❌ 无法加载文件 {file_path}: {e}")
        return None

def analyze_psqi_data(data, file_name):
    """分析PSQI数据完整性"""
    print(f"\n=== {file_name} 分析 ===")
    
    # 检查基本信息字段
    basic_fields = ['surveyId', 'patientName', 'age', 'gender']
    print("\n📋 基本信息字段:")
    for field in basic_fields:
        if field in data:
            print(f"  ✅ {field}: {data[field]}")
        else:
            print(f"  ❌ 缺少字段: {field}")
    
    # 检查PSQI问卷字段 (SL01-SL10系列)
    psqi_fields = [
        'SL01', 'SL02', 'SL03', 'SL04', 'SL051', 'SL052', 'SL053', 'SL054', 'SL055',
        'SL056', 'SL057', 'SL058', 'SL059', 'SL05X', 'SL05X1', 'SL06', 'SL07', 'SL08',
        'SL09', 'SL10', 'SL101', 'SL102', 'SL103', 'SL104', 'SL10X', 'SL105'
    ]
    
    print("\n📝 PSQI问卷字段:")
    found_psqi_fields = 0
    for field in psqi_fields:
        if field in data:
            print(f"  ✅ {field}: {data[field]}")
            found_psqi_fields += 1
        else:
            print(f"  ❌ 缺少字段: {field}")
    
    print(f"\n📊 问卷字段完整性: {found_psqi_fields}/{len(psqi_fields)} ({found_psqi_fields/len(psqi_fields)*100:.1f}%)")
    
    # 检查计算结果字段
    print("\n🧮 计算结果字段:")
    if 'totalScore' in data:
        print(f"  ✅ totalScore: {data['totalScore']}")
    else:
        print("  ❌ 缺少 totalScore")
    
    # 检查英文字段名
    english_fields = [
        'subjective_sleep_quality', 'sleep_latency', 'sleep_duration', 
        'sleep_efficiency', 'sleep_disturbance', 'sleep_medication', 'daytime_dysfunction'
    ]
    
    english_count = 0
    for field in english_fields:
        if field in data:
            print(f"  ✅ {field}: {data[field]}")
            english_count += 1
    
    # 检查中文字段名（旧格式）
    chinese_fields = [
        '主观睡眠质量_score', '入睡时间_score', '睡眠时间_score', '睡眠效率_score',
        '睡眠干扰_score', '催眠药物的使用_score', '日间功能障碍_score'
    ]
    
    chinese_count = 0
    for field in chinese_fields:
        if field in data:
            print(f"  ⚠️  旧字段 {field}: {data[field]}")
            chinese_count += 1
    
    print(f"\n📈 字段格式: 英文字段 {english_count}/7, 中文字段 {chinese_count}/7")
    
    return {
        'basic_fields': len([f for f in basic_fields if f in data]),
        'psqi_fields': found_psqi_fields,
        'english_fields': english_count,
        'chinese_fields': chinese_count,
        'total_fields': len(data)
    }

def main():
    print("🔍 PSQI数据文件对比分析")
    print("=" * 50)
    
    # 文件路径
    old_file = "survey_data/5/PSQI睡眠质量评估结果_5_5_2025-09-22T02-54-21.json"
    new_file = "survey_data/psqi_surveys/test_complete_data.json"
    
    # 检查文件是否存在
    if not os.path.exists(old_file):
        print(f"❌ 旧文件不存在: {old_file}")
        return
    
    if not os.path.exists(new_file):
        print(f"❌ 新文件不存在: {new_file}")
        return
    
    # 加载数据
    old_data = load_json_file(old_file)
    new_data = load_json_file(new_file)
    
    if not old_data or not new_data:
        return
    
    # 分析数据
    old_stats = analyze_psqi_data(old_data, "修复前文件")
    new_stats = analyze_psqi_data(new_data, "修复后文件")
    
    # 对比总结
    print("\n" + "=" * 50)
    print("📊 修复效果对比总结")
    print("=" * 50)
    
    print(f"基本信息字段: {old_stats['basic_fields']} → {new_stats['basic_fields']}")
    print(f"PSQI问卷字段: {old_stats['psqi_fields']}/26 → {new_stats['psqi_fields']}/26")
    print(f"英文结果字段: {old_stats['english_fields']}/7 → {new_stats['english_fields']}/7")
    print(f"中文结果字段: {old_stats['chinese_fields']}/7 → {new_stats['chinese_fields']}/7")
    print(f"总字段数量: {old_stats['total_fields']} → {new_stats['total_fields']}")
    
    # 修复效果评估
    if new_stats['psqi_fields'] > old_stats['psqi_fields']:
        print("\n✅ 修复成功！问卷数据字段已完整保存")
    else:
        print("\n❌ 修复未完成，问卷数据仍有缺失")
    
    if new_stats['english_fields'] > old_stats['english_fields']:
        print("✅ 字段名称已更新为英文格式")
    
    if new_stats['chinese_fields'] < old_stats['chinese_fields']:
        print("✅ 旧的中文字段名已清理")

if __name__ == "__main__":
    main()